#!/usr/bin/perl
#
# Richard Harvey 11/06/2008
# Version 1.3
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# e-mail:richard@squarecows.com

use strict;
use HTTP::Request::Common qw(POST); # libhttp-request-ascgi-perl
use LWP::UserAgent; # liblwpx-paranoidagent-perl libcrypt-ssleay-perl

############################
#### USER CONFIGURATION ####
############################

# Use in the format ("firewall_1_details", "firewall_2_details", etc etc) for all 3 variables
my @address = ("fw1.example.com","fw2.example.com");
my @username = ("admin_1","admin_2");
my @password = ("pass_1","pass_2");

# Do the firewalls use http = 0 or https = 1
my $secure = 1;

# Do you want a verbose output? 0 = NO 1 = YES
my $verbose = 1;

# Specify your own backup Dir
my $backup_dir = "/home/rjharv/Documents/Projects/m0n0wall";

# Do you want to automatically remove old backups 0 = NO, 1 = YES
my $rembackups = 1;

# Set to 0 to only keep current config else specify number of days you want to keep backups for
my $numbackups  = 5;

# Set to 1 if you wish your old backups to be compressed. 0 to leave alone.

my $compress_backups = 1;

my $gzip = "/bin/gzip";

###################################
#### END OF USER CONFIGURATION ####
###################################

#######################################################
## Only edit below if your changing the program!!!!! ##
#######################################################

if ($verbose == 1) {
# Convert unix time to date
 my ($sec,$min,$hour,$mday,$mon,$year) = localtime(time);
 my $date  = sprintf("%0.2d.%0.2d.%0.4d",$mday,++$mon,$year+1900);
 my $timestamp = "$date";
# Display Report Header
 print "m0n0wall Backup Utility Report for $date\n\n";
}

# Check Backup Directory is writable
if (-w $backup_dir) {

# Remove old backups if user wishes
if ($rembackups == 1) {
	if ($numbackups == 0 ) {
 	 print "Removing Old Backups.\n\n";
	 system "rm $backup_dir/config-*.xml";
	}
	else {
 	 print "Removing Backups older than $numbackups days.\n\n";
 	 #system "find $backup_dir/ -name \"config-*.xml\" -daystart -atime +$numbackups -exec ls -l {} \\;";
	 system "find $backup_dir -name \"config-*.xml\" -mtime +$numbackups -exec ls -l {} \\;";
	 system "find $backup_dir -name \"config-*.xml\" -mtime +$numbackups -exec rm {} \\;";
	 #system "find $backup_dir/ -name \"config-*.xml\" -daystart -atime +$numbackups -exec rm {} \\;";
	 print "\n";
	}
}

# Compress old .xml files if the user wishes
if ($compress_backups == 1) {
	print "Removing Gzip'ing Backups\n\n";
	system "find $backup_dir -name \"config-*.xml\" -exec $gzip {} \\;";
	print "\n";
}

# Initiate Firewall Loop Counter
my $fw_number = 0;

# Firewall Count Loop
foreach (@address) {

# Display Output to show whats happening
	if ($verbose == 1) {
	 print "Backing up $_.\n";
	}

# Select Protocol
	my $proto;
	if ($secure == 1) {
	 $proto = "https";
	}
	else {
	 $proto = "http";
	}

# Connect to the Firewall with password for HTTP Auth and submit a POST
my $ua=LWP::UserAgent->new();
my $req= POST "$proto://$_/diag_backup.php", [ "Submit" => "Download configuration" ];
$req->authorization_basic($username[$fw_number], $password[$fw_number]);
$req->content_type('application/x-www-form-urlencoded');

# Send Request
my $content=$ua->request($req)->as_string;
# Currenlty Required for error checking!
my $check=$ua->request($req);

	if ($check->is_success) {

	 my @lines = split /\n/, $content;
	 my @filename;
	 if ($secure == 1) {
 	  @filename = split /\=/, @lines[10];
	 }
	 else {
	  @filename = split /\=/, @lines[6];
	 }

# Write the file
		if ($verbose == 1) {
		  print "Writing @filename[1]\n\n";
		}
	 my $count = 0;
# Decide how many lines to ignore. This may need tweeking to accomadate valid SSL certs!
		my $ig_lines;
		if ($secure == 1) {
		 $ig_lines = 12;
		}
		else {
		 $ig_lines = 8;
		}
	 open (MYFILE, ">$backup_dir/@filename[1]");
	# Drop the first 12 lines we dont need them this is just perl output!
		foreach (@lines) {
		  if ($count > $ig_lines) {
		    print MYFILE "$_\n";
		  }
		 $count++;
		}
# Commit file to disk
	close (MYFILE);
	}
	else {
	 print "Error Could Not Backup $_!!!\n\n";
	}
# Move the Firewall count on incase we need to access information for a second+ firewall
$fw_number++;
}
}
else {
 print "Error $backup_dir is not writable or does not exist!!!\n\n"
}
